package com.example.musicplayer

import android.content.*
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.util.Log
import android.widget.SeekBar
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import java.text.SimpleDateFormat
import java.util.*


class MainActivity : AppCompatActivity() {

    var musicController: MusicService.MusiceController? = null
    lateinit var handler: Handler

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        handler = Handler(Looper.getMainLooper())
        val intent = Intent(this, MusicService::class.java)
        //增加StartService，来增加后台播放功能
        //增加StartService，来增加后台播放功能
        startService(intent)
        // 绑定服务，使用context来绑定
        // 那个界面需要绑定 就用哪个 Activity
        // 参数1：Intent               代表需要绑定哪一个Service
        // 参数2：ServiceConnection    回调接口，可以接收到Service连接成功和断开的回调，成功就可以取到对象。
        // 绑定服务 参数2就是服务和指定的对象绑定在一起
        // 绑定服务，使用context来绑定
        // 那个界面需要绑定 就用哪个 Activity
        // 参数1：Intent               代表需要绑定哪一个Service
        // 参数2：ServiceConnection    回调接口，可以接收到Service连接成功和断开的回调，成功就可以取到对象。
        // 绑定服务 参数2就是服务和指定的对象绑定在一起
        bindService(intent, MusicConnection(), Context.BIND_AUTO_CREATE)
        btPlay.setOnClickListener {
            musicController?.play()
            startRefreshSeekbar()
        }
        btPause.setOnClickListener { musicController?.pause() }
        btNext.setOnClickListener { musicController?.next() }
        btPrevious.setOnClickListener { musicController?.previous() }
        sb.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {

            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                musicController?.seekTo(seekBar?.progress ?: 0)
            }

        })

        val iF = IntentFilter()
        iF.addAction("com.android.music.metachanged")
        iF.addAction("com.android.music.playstatechanged")
        iF.addAction("com.android.music.playbackcomplete")
        iF.addAction("com.android.music.queuechanged")

        registerReceiver(mReceiver, iF)
        registerReceiver(infoUpdateBroadcastReceiver, IntentFilter(ACTION_UPDATE_INFO))

    }

    private fun startRefreshSeekbar() {
        handler.removeCallbacks(mRefreshRunnable)
        handler.removeCallbacks(mNextRefresgRunnable)
        if (musicController?.isPlaying() == true) {
            handler.post(mRefreshRunnable)
            handler.postDelayed(mNextRefresgRunnable, 500)
        }
    }

    inner class MusicConnection : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName?) {
            musicController = null
        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            musicController = service as MusicService.MusiceController?
        }

    }

    private val mReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent) {
            val action = intent.action
            val cmd = intent.getStringExtra("command")
            Log.d("onReceive ", "$action / $cmd")
            val artist = intent.getStringExtra("artist")
            val album = intent.getStringExtra("album")
            val track = intent.getStringExtra("track")
            Log.d("Music", "$artist:$album:$track")
            tvSongName.text = "$artist:$album:$track"
        }
    }

    private val mRefreshRunnable = object : Runnable {
        override fun run() {
            try {
                if (musicController?.isPlaying() == true) {
                    if (musicController != null) {
                        val musicDuration = musicController?.getDuration()
                        val position = musicController?.getPosition()
                        val dateTotal = Date(musicDuration ?: 0)
                        val sdf = SimpleDateFormat("mm:ss")
                        sb.setMax(musicDuration?.toInt() ?: 0)
                        sb.setProgress(position?.toInt() ?: 0)
                        tvTime.post(
                                Runnable {
                                    val date = Date(position ?: 0)
                                    val time: String = sdf.format(date).toString() + "/" + sdf.format(dateTotal)
                                    tvTime.setText(time)
                                }
                        )
                    }
                }
            } catch (e: InterruptedException) {
                e.printStackTrace()
            }
        }
    }

    private val mNextRefresgRunnable = object : Runnable {
        override fun run() {
            startRefreshSeekbar()
        }
    }

    var infoUpdateBroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            tvSongName.setText(info)
        }
    }

    companion object {
        var info: String? = null
        val ACTION_UPDATE_INFO = "com.example.musicplayer.UPDATE_INFO"
    }
}